package com.kgc.ssm.filter;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class ShiroUserFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        Subject subject = SecurityUtils.getSubject();
        if ((subject.isAuthenticated() || subject.isRemembered()) && request.getSession().getAttribute("userName") == null) {
            String userName = (String) subject.getPrincipal();
            request.getSession().setAttribute("userName", userName);
        }
        filterChain.doFilter(request, response);
    }
}

